<?php

namespace app\api\model;

use think\Log;
use think\Cache;
use think\Db;
use app\service\VideoModerationTask;

class ShenheTask extends Common
{
    static public function CreateTask($user_id, $order_id)
    {
        // $Cache = Cache::get('ShenheTask:'.$order_id);
        // if ($Cache) {
        //     return true;
        // }
        $config = Db::name('config_system')->master()->where(['title'=>['in', ['lianmai_shenhe_lasttime','lianmai_shenhe_lastlongtime']]])->column('content', 'title');
        $hasTask = Db::name('shenhe_task')->master()->where(['order_id'=>$order_id])->select();
        $taskid = '';
        $timenow = time();
        $cancel = false;
        if ($config['lianmai_shenhe_lasttime']) {
            $tasklen = sizeof($hasTask);
            if ($tasklen>=2) return true;
            if ($tasklen==1){
                if ($hasTask[0]['create_time']+$config['lianmai_shenhe_lasttime'] + $config['lianmai_shenhe_lastlongtime'] - 9 < $timenow) {
                    $taskid = $hasTask[0]['task_id'];
                }elseif ($hasTask[0]['create_time']+$config['lianmai_shenhe_lasttime']-$config['lianmai_shenhe_lastlongtime']-8 < $timenow) {
                    $taskid = $hasTask[0]['task_id'];
                    $cancel = true;
                }else {
                    return true;
                }
            } else {
                // Cache::set('ShenheTask:'.$order_id, $order_id, 2);
            }
        } else {
            Cache::set('ShenheTask:'.$order_id, $order_id, 2);
            if (sizeof($hasTask)) return true;
        }
        $chat = Db::name('privatechat')->master()->where(['order_id'=>$order_id])->find();
        $appid = getenv('TLS_APPID');
        if ($chat['data']) {
            $appid = json_decode($chat['data'], true)['trtc_appid'] ?? $appid;
        }
        if ($cancel) {
            VideoModerationTask::cancelTask($appid, $taskid);
            return true;
        }
        $time = time();
        try {
            $task = VideoModerationTask::createTask($user_id, $order_id, $appid, $taskid);
        } catch (\Exception $e) {
            Log::write($e->getMessage(),'error');
        }
        if ($task) {
            $TaskId = $task['Results'][0]['TaskId'];
            self::create([
                'task_id' => $TaskId,
                'order_id' => $order_id,
                'create_time' => $time,
                'update_time' => $time
            ]);
        }
    }
}
